<template>
  <el-pagination
    v-model:current-page="pageable.pageNum"
    v-model:page-size="pageable.pageSize"
    :page-sizes="pageable.pageSizes"
    :size="size"
    :background="background"
    :layout="layout"
    :total="modelValue.total"
    v-bind="$attrs"
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
  />
</template>

<script lang="ts" setup name="EcoPagination">
import type { ComponentSize } from 'element-plus'
const pageableSetting = { pageNum: 1, pageSizes: [10, 20, 50, 100, 200], pageSize: 20 }

interface PaginationProps {
  layout?: string
  background?: boolean
  reset?: boolean
}

const props = withDefaults(defineProps<PaginationProps>(), {
  layout: 'total, sizes, prev, pager, next, jumper',
  background: true,
  reset: true
})
const pageable = defineModel<EcoTable.Pageable>({ required: true })
const emits = defineEmits<{ pagination: [value: EcoTable.Pageable] }>()

if (!unref(pageable).pageNum) pageable.value.pageNum = pageableSetting.pageNum
if (!unref(pageable).pageSizes) pageable.value.pageSizes = pageableSetting.pageSizes
if (!unref(pageable).pageSize) pageable.value.pageSize = pageableSetting.pageSize

const handleSizeChange = (value: number) => {
  if (props.reset) handleCurrentChange(1)
  pageable.value.pageSize = value
  afterChange()
}

const handleCurrentChange = (value: number) => {
  pageable.value.pageNum = value
  afterChange()
}

const afterChange = () => {
  pageable.value = unref(pageable)
  emits('pagination', unref(pageable))
}

const size = ref<ComponentSize>('default')

defineExpose({ pageable: pageableSetting })
</script>
<style lang="scss" scoped></style>
